package com.example.dqnm.service.impl;

import com.example.dqnm.mapper.OrdersDao;
import com.example.dqnm.pojo.Orders;
import com.example.dqnm.pojo.OrdersExample;
import com.example.dqnm.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Service
public class OrdersServiceImpl implements OrderService {
    @Autowired
    private OrdersDao ordersDao;
    private final AtomicInteger orderSequence = new AtomicInteger(0);

    @Override
    public Boolean insertOrders(Orders orders) {
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        String currentDate = dateFormat.format(date);
        // 生成序列号，确保每天从 1 开始
        int sequence = orderSequence.incrementAndGet();

        // 格式化序列号（例如，固定为6位，不足补零）
        String formattedSequence = String.format("%06d", sequence);
        orders.setOrdertime(date);
        orders.setOrderstatus("制作中");
        orders.setOrdernum(currentDate + formattedSequence);
        int insert = ordersDao.insert(orders);
        return insert > 0;
    }

    @Override
    public List<Orders> findAllOrdersByUserId(Integer id, String orderStatus) {
        OrdersExample ordersExample = new OrdersExample();
        ordersExample.setOrderByClause("orderTime desc");
        OrdersExample.Criteria criteria = ordersExample.createCriteria();
        criteria.andUseridEqualTo(id);
        criteria.andOrderstatusEqualTo(orderStatus);
        return ordersDao.selectByExample(ordersExample);
    }

    /**
     * 每天凌晨00:00重置订单序列号
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void resetOrderSequence() {
        orderSequence.set(0);
        System.out.println("订单序列号已重置: " + orderSequence.get());
    }
}
